/*
 *  Copyright 2011 jmarsden.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package cc.plural.jsonij.jpath;

import java.util.List;

import cc.plural.jsonij.Value;

/**
 *
 * @author jmarsden
 */
public class KeyComponent extends Component {

    String value;

    public KeyComponent(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return String.format("KeyComponent [%s]", value);
    }

    @Override
    public List<Value> evaluate(List<Value> values, List<Value> results) {
        Value valueStore = null;
        for(Value currentValue: values) {
            String keyValue = getValue();
            if(currentValue.getValueType() == Value.TYPE.OBJECT) {
                valueStore = currentValue.get(keyValue);
                if(valueStore != null) {
                    results.add(valueStore);
                }
            } else if(currentValue.getValueType() == Value.TYPE.ARRAY) {
                for(int j=0;j<currentValue.size();j++) {
                    valueStore = currentValue.get(j).get(keyValue);
                    if(valueStore != null) {
                        results.add(valueStore);
                    }
                }
            }
        }
        return results;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final KeyComponent other = (KeyComponent) obj;
        return this.value.equals(other.value);
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 53 * hash + ( this.value != null ? this.value.hashCode() : 0 );
        return hash;
    }
}
